<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryFormRef" :inline="true">
      <el-form-item prop="tableName" label="表名称">
        <el-input v-model="queryForm.tableName" placeholder="请输入表名称" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item prop="tableComment" label="表描述">
        <el-input v-model="queryForm.tableComment" placeholder="请输入描述" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-space>
          <span>
            <el-button type="primary" @click="handleQuery" icon="Search"> 搜索</el-button>
            <el-button @click="handleResetQuery" icon="Refresh"> 重置</el-button>
          </span>
        </el-space>
      </el-form-item>
    </el-form>

    <el-divider />

    <!-- action -->
    <div class="action">
      <el-space>
        <el-button type="primary" @click="openImportTable" icon="Plus">导入 </el-button>
        <el-button type="primary" status="danger" @click="() => { deleteVisible = true; }" icon="Delete">
          批量删除</el-button>
      </el-space>
    </div>

    <!-- table -->
    <el-table :data="tableData" row-key="tableId" layout="auto">
      <el-table-column label="序号" prop="tableId" :width="180" />
      <el-table-column label="表名称" prop="tableName" :width="180" />
      <el-table-column label="表描述" prop="tableComment" :width="180" />
      <el-table-column label="模型名称" prop="className" :width="180" />
      <el-table-column label="动作" :width="370" align="center">
        <template #default="scope">
          <!-- <el-button-group> -->
          <el-button size="small" @click="handleEditTable(scope.row)">编辑</el-button>
          <el-button size="small" @click="handlePreview(scope.row)">预览</el-button>
          <el-popconfirm title="正在使用代码生成请确认?" confirm-button-text="生成" icon="Warning"
            @confirm="handleToProject(scope.row)">
            <template #reference>
              <el-button size="small">代码生成 </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="正在使用【菜单以及API生成到数据库】请确认?" confirm-button-text="写入DB" icon="Warning"
            @confirm="handleToDB(scope.row)">
            <template #reference>
              <el-button size="small">生成配置 </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="正在使用代码生成配置迁移脚本请确认?" confirm-button-text="迁移" icon="Warning"
            @confirm="handleToApiFile(scope.row)">
            <template #reference>
              <el-button size="small">生成迁移脚本 </el-button>
            </template>
          </el-popconfirm>
          <el-button size="small"
            @click="() => { deleteVisible = true; deleteData = [scope.row.tableId];  }">删除</el-button>
          <!-- </el-button-group> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 导入对话框 -->
    <import-table v-model="modalVisible" @on-close="modalVisible = false" />

    <!-- 预览代码对话框 -->
    <el-dialog v-model="codeVisible" title="预览代码" width="80%">
      <el-space style="margin-bottom: 16px;">
        <el-button v-for="(value, key) of preview.data" :key="key" bordered @click="codeChange(key)">{{
          key.substring(key.lastIndexOf('/')+1,key.indexOf('.go.template')) }}</el-button>
      </el-space>
      <!-- 代码编辑器 -->
      <codemirror v-model="codestr" :style="{ height: '600px' }" :autofocus="true" :indent-with-tab="true" :tab-size="2"
        :extensions="extensions" />
    </el-dialog>

    <!-- Akiraka 20230223 删除与批量删除 开始 -->
    <DeleteModal :data="deleteData" :visible="deleteVisible" :apiDelete="handleDelTable"
      @deleteVisibleChange="() => deleteVisible = false" />
    <!-- Akiraka 20230223 删除与批量删除 结束 -->
  </div>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue';
import importTable from './importTable.vue'
import { listTable,previewTable,delTable,apiToFile,toProjectTableCheckRole,toDBTable } from '@/api/tools/gen';
import { parseTime } from '@/utils/parseTime';
import { Codemirror } from 'vue-codemirror'
import { javascript } from '@codemirror/lang-javascript'
import { oneDark } from '@codemirror/theme-one-dark'

// Akiraka 20230210 删除数据
const deleteData = ref([])
// Akiraka 20230210 删除对话框
const deleteVisible = ref(false)
const queryFormRef = ref({});
// Akiraka 20230210 监听删除事件
watch(() => deleteVisible.value ,(value) => {
  if ( value == false ) {
    handleQuery()
  }
})

const { proxy } = getCurrentInstance();

const currentPage = ref(1);
// Pager
const pager = {
  count: 0,
  pageIndex: 1,
  pageSize: 10,
};
// form
const queryForm = reactive({});
const modalForm = reactive({
  sort: 0,
  status: 2,
});

const modalVisible = ref(false);
const openImportTable = () => {
  modalVisible.value = true;
};
// Batch Del List
let batchList = [];

// Table Data
const tableData = ref([]);

// 修改
const handleUpdate = async (record) => {
  modalVisible.value = true;
  modalTitle.value = '修改岗位';
  await nextTick();
  Object.assign(modalForm, record);
};

// Table 勾选数据
const selectionChange = (rowKeys) => {
  batchList = rowKeys;
};

/**
 * 分页改变
 * @param {Number} [page]
 */
 const handlePageChange = (page) => {
  pager.pageIndex = page;
  // 修改当前页码
  currentPage.value = page;
  getListTable({ ...pager, ...queryForm });
};

// 每页数据量
const handlePageSizeChange = (pageSize) => {
  pager.pageSize = pageSize;
  getListTable({ ...pager, ...queryForm });
};

// 获取列表数据
const getListTable = async (params = {}) => {
  const { data, code, msg } = await listTable(params);
  if ( code == 200 ) {
    tableData.value = data.list;
    Object.assign(pager, { count: data.count, pageIndex: data.pageIndex, pageSize: data.pageSize });
  } else {
    proxy.$message.error(msg);
  }
};

// 查询列表信息
const handleQuery = async () => {
  const params = {
    pageIndex: pager.pageIndex,
    pageSize: pager.pageSize,
    ...queryForm,
  };

  getListTable(params);
};

// 重置搜索
const handleResetQuery = () => {
  queryFormRef.value.resetFields();
  getListTable(queryForm);
}

// 按钮块
// 编辑
const handleEditTable = (row) => {
  const tableId = row.tableId || this.ids[0]
  proxy.$router.push({ path: '/dev-tools/editTable', query: { tableId: tableId }})
}
// 预览代码参数
// 预览代码对话框
const codeVisible = ref(false);
// 预览参数
const preview = ref({
  open: false,
  title: '代码预览',
  data: {},
  activeName: 'api.go'
})
/** 预览按钮 */
const handlePreview = (row) => {
  codeVisible.value = true;
  previewTable(row.tableId).then(response => {
    preview.value.data = response.data
    preview.value.open = true
    codeChange('template/api.go.template')
  })
}
// 代码编辑器参数
const cmOptions = ref({
  tabSize: 4,
  theme: 'material-palenight',
  mode: 'text/javascript',
  lineNumbers: true,
  line: true
})
const extensions = [javascript(), oneDark];
const codestr = ref('')
// 预览代码 代码更改
const codeChange = (e) => {
  if (e.indexOf('ts') > -1) {
    
    cmOptions.value.mode = 'text/javascript'
  }
  if (e.indexOf('model') > -1 || e.indexOf('router') > -1 || e.indexOf('api') > -1 || e.indexOf('service') > -1 || e.indexOf('dto') > -1) {
    cmOptions.value.mode = 'text/x-go'
  }
  if (e.indexOf('vue') > -1) {
    cmOptions.value.mode = 'text/x-vue'
  }
  codestr.value = preview.value.data[e]
}
// 代码生成
const handleToProject = (row) => {
  console.log("dasdasd",row)
  toProjectTableCheckRole(row.tableId, false).then((response) => {
    proxy.$message.success(response.msg);
  }).catch(function() {})
}
// 生成配置
const handleToDB = (row) => {
  toDBTable(row.tableId).then((response) => {
    proxy.$message.success(response.msg);
  }).catch(function() {})
}
// 生成迁移脚本
const handleToApiFile = (row) => {
  apiToFile(row.tableId, true).then((response) => {
    proxy.$message.success(response.msg);
  }).catch(function() {})
}

const handleDelTable = (tabs) => {
   const idgroup = tabs.ids.join(",")
  return delTable(idgroup)
}

onMounted(() => {
  getListTable(pager);
});
</script>

<style lang="scss">
.action {
  margin-bottom: 12px;
}</style>
